import webapp2
import cgi
import logging
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app

from collections import defaultdict

from django.utils import simplejson


from models.brewery import Brewery

################		
class BreweryHandler(webapp2.RequestHandler):
	
	def post(self):
		#logger = logging.getLogger('brewery_app')
		#logger.setLevel(logging.DEBUG)
		#logger.info('form_name: ')
		
		## NEED TO ADD A LOT OF ERROR CHECKING.
		brewery_name = cgi.escape(self.request.get('brewery_name'))
		if (brewery_name != ''):
			brewery_desc = cgi.escape(self.request.get('brewery_desc'))
			#logger.info(form_name)
			if (brewery_name != None):
				brwy = Brewery()
				brwy.name = brewery_name
				brwy.description = brewery_desc
				brwy.put()
				newbrwy = Brewery.all().filter('name =', brewery_name).get()
				brwyid = newbrwy.key().id()
				#self.redirect('/breweries?id=' + str(brwyid))
				self.response.out.write("<html><body><p>Brewery Created</p></body></html>")
		else:
			self.response.out.write("<html><body><p>An Error Occured</p></body></html>")
		
	def get(self):
		tag = self.request.get('id')
		if (tag):
			if (tag == "all"):
				output = []
				breweries = Brewery.all().order('name')
				for brwry in breweries:
					output.append(brwry.to_dict())
				self.response.out.write(simplejson.dumps({'breweries': output}).replace("\/", "/"))
			else:
				output = []
				bId = int(tag)
				if (bId > 0):
					brwry = Brewery.get_by_id(bId)
					if brwry != None:
						output.append(brwry.to_dict()) 
				self.response.out.write(simplejson.dumps({'brewery': output}).replace("\/", "/"))
		else :
			
			output = []
			breweries = Brewery.all().order('name')
			for brwry in breweries:
				output.append(brwry.to_dict())
			self.response.out.write(simplejson.dumps({'breweries': output}).replace("\/", "/"))
			
################		
class AddBreweryHandler(webapp2.RequestHandler):
	
	def get(self):
		self.response.out.write("""
				<html>
				<body>
			""")
		self.response.out.write("""
			<form action="/breweries" method="post">
			<div>Brewery Name: <input type="text" name="brewery_name" /></div>
			<div>Description: <input type="text" name="brewery_desc" /></div>
			<div><input type="submit" value="Create Brewery"></div>
			</form>""")
		self.response.out.write('</body></html>')

app = webapp2.WSGIApplication([
	('/breweries/add', AddBreweryHandler),
	('/breweries', BreweryHandler)
   
], debug=True)
